<template>
  <div>
    <div style="margin-bottom: 10px">
      <el-input v-model="params.name" placeholder="请输入书名" style="width: 200px"></el-input>
      <el-input v-model="params.author" placeholder="请输入作者" style="width: 200px"></el-input>
      <el-button type="warning" style="margin: 10px" @click="findBySearch()">查询</el-button>
      <el-button type="warning" style="margin: 10px" @click="reset()">清空</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add()" v-if="user.role !== 'ROLE_STUDENT'">新增</el-button>
    </div>

    <div class="about">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="img" label="图片">
          <template v-slot="scope">
            <el-image
                style="width: 70px; height: 70px; border-radius: 50%"
                :src= "'http://localhost:8080/api/files/' + scope.row.img"
                :preview-src-list="['http://localhost:8080/api/files/' + scope.row.img]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column  label="图书介绍">
          <template slot-scope="scope">
            <el-button type="text" @click="showDetail(scope.row.content)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="图书书名" width="180"></el-table-column>
        <el-table-column prop="author" label="图书作者" width="180"></el-table-column>
        <el-table-column prop="press" label="图书出版社"></el-table-column>
        <el-table-column prop="price" label="图书价格"></el-table-column>
        <el-table-column prop="typeName" label="图书分类"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)" v-if="user.role === 'ROLE_ADMIN'">编辑</el-button>
            <el-button type="primary" @click="down(scope.row.img)">下载</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger" style="margin-left: 5px" v-if="user.role === 'ROLE_ADMIN'">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

<!--  分页插件  -->
    <div style="margin-top: 10px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

<!--  新增、编辑  -->
    <div>
      <el-dialog title="请填写信息" :visible.sync="dialogFormVisible" width="50%">
        <el-form :model="form">
          <el-form-item label="图书名" label-width="20%">
            <el-input v-model="form.name" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="图书封面" label-width="20%">
            <el-upload action="http://localhost:8080/api/files/upload" :on-success="successUpload">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="图书价格" label-width="20%">
            <el-input v-model="form.price" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="图书作者" label-width="20%">
            <el-input v-model="form.author" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="图书出版社" label-width="20%">
            <el-input v-model="form.press" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="图书分类" label-width="20%">
            <el-select v-model="form.typeId" placeholder="请选择">
              <el-option
                  v-for="item in typeObjs"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图书介绍" label-width="20%">
            <div id="editor"></div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>

<!-- 查看内容的对话框 -->
    <div>
      <el-dialog title="图书内容" :visible.sync="editorVisible" width="50%">
        <div v-html="this.form.content" class="w-e-text"></div>
      </el-dialog>
    </div>

  </div>
</template>


<script>
import request from "@/utils/request"

import E from 'wangeditor'

let editor;
function initEditor(content){ setTimeout( () => {
   // 这个不为空时，才初始化。
   if(!editor){
     editor = new E('#editor');
     editor.config.placeHolder = '请输入内容';
     editor.config.uploadFileName = 'file';
     editor.config.uploadImgServer = 'http://localhost:8080/api/files/wang/upload';
     editor.create();
   }
    editor.txt.html(content); //写入内容
  }, 0)

}

export default {
  data() {
    return {
      url: "http://localhost:8080/api/files/",
      total: 0,
      params:{
        name: '',
        author: '',
        pageSize:5,
        pageNum:1
      },
      input:'',
      tableData: [],
      form: {},  //form表单对象
      dialogFormVisible: false,  //模态框显示/不显示
      editorVisible: false,  //模态框显示/不显示(图书内容的对话框)

      typeObjs:[],  //存放查询出来的所有图书分类信息对象的数据
      user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {},
    }
  },
  // 页面加载时
  created() {
    this.findBySearch();
    //一打开图书信息页面时就要查询所有的分类信息
    this.findTypes();
  },
  // 页面按钮触发事件时使用的方法
  methods: {
    findTypes(){
      request.get('/type').then(res => {
        if (res.code === '0'){
          this.typeObjs = res.data;
        }else {
          this.$message.error('获取分类信息失败');
        }
      })
    },


    //1. 点击查看，展示图书内容
    showDetail(data){
        this.form.content = data;
        this.editorVisible = true;
    },


    //2. 模糊查询 + 添加分页
    findBySearch(){
      request.get('/book/search',{params : this.params}).then(res => {
        if (res.code === '0'){
          this.tableData = res.data.list;
          this.total = res.data.total;
        }else {

        }
      })
    },

    //3. 清空查询框
    reset(){
      this.params = {
          phone: '',
          name: '',
          pageNum: 1,
          pageSize: 5
      }
      this.findBySearch()
    },

    //4. x条/页 切换
    handleSizeChange(pageSize){  //有回调函数，参数是每页显示条数
      this.params.pageSize = pageSize;
      this.findBySearch();
    },
    //5. 页数切换
    handleCurrentChange(pageNum){  //有回调函数，参数是页数
      this.params.pageNum = pageNum;
      this.findBySearch();
    },

    //6.新增图书
    add(){
      this.form = {};  //原本有个bug,每次新增前，先清空form表单就解决了
      // 展示富文本框
      initEditor("");
      this.dialogFormVisible = true;
    },

    //7. 编辑图书
      edit(obj){
          this.form = obj;
          // 回显富文本中原有的内容，为了解决bug，先判断该字段是否有内容，有则展示，没有则不展示
          initEditor(this.form.content ? this.form.content : "");
          this.dialogFormVisible = true;
      },


    submit(){
      // 1. 特殊：获取富文本框的内容，要单独获取，因为他不在<input>输入框中，因此原本的this.form中没有content值
      this.form.content = editor.txt.html();
      // 2. 提交表单
      request.post('/book',this.form).then(res => {
        if (res.code === '0'){
          //成功
          this.$message.success('操作成功')
          this.dialogFormVisible = false;
          this.findBySearch();
        }else {
          //失败
          this.$message.error(res.msg)
        }
      })
    },



    //8.删除
    del(id){
      request.delete('/book/'+id).then(res => {
        if (res.code === '0'){
          this.$message.success('操作成功')
          this.findBySearch()
        }else {
          this.$message.error(res.msg)
        }
      })
    },


    // 文件上传成功后的钩子:这里只是上传，还没点击确定，就是看能不能上传到成功
    successUpload(res){  // 回调参数
      // 把上传成功之后，后端返回值拿过来存储
      // 返回的是时间戳， 属于文件名的一部分，到时候把这个唯一值存储到数据库，就有了对应关系，就好办了。
      this.form.img = res.data;
    },

    // 文件下载到本地
    down(flag){
      location.href = 'http://localhost:8080/api/files/' + flag
    }
  }
}
</script>
